package com.leetao.ifkiller.core.impl;

import com.leetao.ifkiller.core.CommandExecutor;
import com.leetao.ifkiller.core.CommandIssuer;
import com.leetao.ifkiller.domain.Command;
import com.leetao.ifkiller.domain.ConsumerPro;
import com.leetao.ifkiller.domain.PredicatePro;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 *  流程处理程序
 *
 * @author 菅江晖
 * @date 2021/6/11 - 0:58
 */
public class ProcessHandler<T> implements CommandIssuer<T> {
    private final T clientele;
    private final List<PredicatePro<T>> predicatePros = new LinkedList<>();
    private CommandExecutor<T> commandExecutor;

    public ProcessHandler(T clientele) {
        this.clientele = clientele;
    }


    @Override
    public CommandIssuer<T> execute(String description, Consumer<T> consumer) {
        if (commandExecutor == null) {
            this.commandExecutor = new CommandExecutorImpl<>(this);
        }

        //添加执行命令
        this.commandExecutor.execute(new Command<>(predicatePros, new ConsumerPro<T>().description(description).consumer(consumer)));
        return this;
    }

    @Override
    public CommandIssuer<T> and(String description, Predicate<T> condition) {
        return add(description, condition);
    }

    @Override
    public CommandIssuer<T> condition(String description, Predicate<T> condition) {
        return new ProcessHandler<T>(clientele).add(description, condition);
    }

    public CommandIssuer<T> add(String description, Predicate<T> condition) {
        this.predicatePros.add(new PredicatePro<T>().description(description).predicate(condition));
        return this;
    }


    public static <T> CommandIssuer<T> create(T clientele) {
        return new ProcessHandler<>(clientele);
    }



    @Override
    public T clientele() {
        return clientele;
    }


}
